﻿(function ($) {
    var methods = {
        init: function (options) {
            var defaultSettings = {
                debug: false,
                src: '',
                messageContainer: null,
                onLoad: null,
                onError: null
            };
            var $this = $(this);

            var data = $this.data('iFrame'),
					iFrame = $(this, {
					});

            // If the plugin hasn't been initialized yet
            if (!data) {
                if (options) {
                    $.extend(defaultSettings, options);
                };
                var o = defaultSettings;

                $(this).data('iFrame', {
                    target: $this,
                    iFrame: iFrame,
                    options: o
                });

                data = $this.data('iFrame');

                jQuery.support.cors = true;
                $this.bind('load.iFrame', function () {
                    methods.onLoad.apply($this);
                    if (typeof (o.onLoad) == 'function') {
                        o.onLoad.apply($this);
                    };
                });
                $this.bind('error.iFrame', function () {
                    methods.onError.apply($this);
                    if (typeof (o.onError) == 'function') {
                        o.onError.apply($this);
                    };
                });
                $(o.messageContainer).show();
                $(o.messageContainer).css('z-index', 9999);
                $this.attr('src', o.src);
            };
            return $this;
        },
        destroy: function () {
            return this.each(function () {
                var $this = $(this),
					data = $this.data('iFrame');

                $this.unbind('.iFrame');
                data.iFrame.remove();
                $this.removeData('iFrame');
            })
        },
        onLoad: function () {
            var $this = $(this),
					data = $this.data('iFrame');
            $(data.options.messageContainer).hide();
        },
        onError: function () {
            var $this = $(this),
					data = $this.data('iFrame');
            $(data.options.messageContainer).hide();
        }
    };

    $.fn.iFrame = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does nost exist on jQuery.iFrame');
        }
    };
})(jQuery);
